package freespiritsocial.io.user.ui.fragment.mine

import android.graphics.Color
import android.os.Bundle
import android.view.ViewGroup
import android.widget.TextView
import com.afollestad.date.dayOfMonth
import com.afollestad.date.month
import com.afollestad.date.year
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgSettingBinding
import freespiritsocial.io.user.ext.getTimeFormat
import freespiritsocial.io.user.ext.goLogin
import freespiritsocial.io.user.ext.hideSoftKeyboard
import freespiritsocial.io.user.ext.str
import freespiritsocial.io.user.handle.BackHandle
import freespiritsocial.io.user.ui.activity.WebActivity
import freespiritsocial.io.user.viewmodel.SettingViewModel
import freespiritsocial.io.user.weight.BottomCancelDialog
import freespiritsocial.io.user.weight.BottomSheetListDialog
import freespiritsocial.io.user.weight.PictureDialog
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.view.isEmpty
import java.util.*

/**
 * @description 设置页
 */
class SettingFrg: BaseFragment<SettingViewModel,FrgSettingBinding>() {
    override fun layoutId(): Int = R.layout.frg_setting
    val pictureDialog by lazy(LazyThreadSafetyMode.NONE) {
        PictureDialog(this,isShowAll = false) {
            if (it.isNotEmpty()) {
                val file = it.first()
                mViewModel.user.value?.userAvatar = if (file.isCompressed) it[0].compressPath else file.realPath
                mViewModel.user.value = mViewModel.user.value
//                mViewModel.updateUserInfo()
            }
        }
    }
    private val minType = booleanArrayOf(true,true,true,false,false,false)
    private val durationPicker: TimePickerView by lazy(LazyThreadSafetyMode.NONE) {
        TimePickerBuilder(requireContext()) { date,_ ->
            mDatabind.tvDob.text = date.getTimeFormat()
        }
            .setLayoutRes(R.layout.layout_time_picker) {
                it.findViewById<TextView>(R.id.btnCancel).setOnClickListener {
                    durationPicker.dismiss()
                }
                it.findViewById<TextView>(R.id.btnSubmit).setOnClickListener {
                    durationPicker.returnData()
                    durationPicker.dismiss()
                }
            }
            .setRangDate(Calendar.getInstance().apply {
                year = 1900
                month = 1
                dayOfMonth = 1
            },Calendar.getInstance())
            .setDate(Calendar.getInstance())
            .setType(minType)
            .setLabel("","","","","","")
            .setContentTextSize(20)
            .setLineSpacingMultiplier(1.8f)
            .setDecorView(
                activity?.window?.decorView
                    ?.findViewById(android.R.id.content) as ViewGroup
            )
            .isDialog(false)
            .setBgColor(Color.WHITE)
            .build()
    }

    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        model = mViewModel
        click = Click()
        mDatabind.tvCountry.setOnCountryChangeListener {
            mDatabind.etName.clearFocus()
            mViewModel.user.value?.country = mDatabind.tvCountry.selectedCountryEnglishName
        }
    }

    override fun createObserver() {
        super.createObserver()
        eventViewModel.changeEmailEvent.observe(this) {
            val user = mViewModel.user.value
            user?.userEmail = it
            mViewModel.user.value = user
        }
    }

    inner class Click: BackHandle {
        fun selectDob() {
            hideSoftKeyboard(requireActivity())
            mDatabind.etName.clearFocus()
            durationPicker.show()
        }

        fun changeEmail() {
            hideSoftKeyboard(requireActivity())
            mDatabind.etName.clearFocus()
            nav().navigateAction(R.id.action_settingFrg_to_changeEmailFrg)
        }

        fun changePassword() {
            hideSoftKeyboard(requireActivity())
            mDatabind.etName.clearFocus()
            nav().navigateAction(R.id.action_settingFrg_to_resetPasswordFrg)
        }

        fun inviteFriends() {
            hideSoftKeyboard(requireActivity())
            mDatabind.etName.clearFocus()
            nav().navigateAction(R.id.action_settingFrg_to_QRFrg)
        }

        fun deleteAccount() {
            hideSoftKeyboard(requireActivity())
            mDatabind.etName.clearFocus()
            BottomCancelDialog(
                requireContext(),
                message = "This operation cannot be undone,Are you sure you want to delete the account?",
                stroke = 1,
                confirmText = R.string.delete.str()
            ) {
                mViewModel.deleteAccount {
                    appViewModel.chatConnectStatus.postValue(false)
                    nav().goLogin()
                }
            }.show(childFragmentManager,"cancel")
        }

        fun logout() {
            hideSoftKeyboard(requireActivity())
            mDatabind.etName.clearFocus()
            mViewModel.logout {
                appViewModel.chatConnectStatus.postValue(false)
                nav().goLogin()
            }
        }

        fun more() {
            hideSoftKeyboard(requireActivity())
            mDatabind.etName.clearFocus()
            BottomSheetListDialog(requireContext(),mViewModel.moreList) {
                when (it) {
                    0 -> WebActivity.launch(requireContext(),"FAQ","https://www.freespiritapp.com/copy-of-privacy-policy")
                    1 -> nav().navigateAction(R.id.action_settingFrg_to_conctactUsFrg)
                    2 -> WebActivity.launch(requireContext(),"Community Guidelines","https://www.freespiritapp.com/copy-of-privacy-policy-1")
                    3 -> WebActivity.launch(requireContext(),"Terms of Use","https://www.freespiritapp.com/terms-and-conditions")
                    4 -> deleteAccount()
                }
            }.show(childFragmentManager,"setting")
        }

        fun uploadAvatar() {
            hideSoftKeyboard(requireActivity())
            mDatabind.etName.clearFocus()
            pictureDialog.show(childFragmentManager,"picture")
        }

        fun removeAvatar() {
            hideSoftKeyboard(requireActivity())
            mDatabind.etName.clearFocus()
            pictureDialog.removeData(mViewModel.user.value?.userAvatar ?: "")
            mViewModel.user.value = mViewModel.user.value?.also { it.userAvatar = "" }
        }

        override fun goBack() {
            if (mDatabind.etName.isEmpty()) {
                mDatabind.etName.error = "Name is not empty!"
                return
            }
            mViewModel.updateUserInfo {
                nav().navigateUp()
            }
        }
    }
}